package cn.smbms.controller.user;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;

import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/jsp/user")
public class UserController {

	@Autowired
	private RoleService roleService;
	@Autowired
	private  UserService userService;


	@RequestMapping("/savepwd")
	private String  updatePwd(String newpassword,HttpSession session,Model model) {
		
		Object o = session.getAttribute(Constants.USER_SESSION);
		System.out.println("1111>>"+o);
		boolean flag = false;
		if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
			
			flag = userService.updatePwd(((User)o).getId(),newpassword);
			System.out.println("2222>>"+flag);
			if(flag){
				model.addAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
				session.removeAttribute(Constants.USER_SESSION);//session注销
			}else{
				model.addAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
			}
		}else{
			model.addAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
		}
		return "pwdmodify";
	}

	@RequestMapping("/pwdmodify")
	@ResponseBody
	private String  getPwdByUserId(String oldpassword,HttpSession session,Model model) {
		Object o = session.getAttribute(Constants.USER_SESSION);

		Map<String, String> resultMap = new HashMap<String, String>();
		
		if(null == o ){//session过期
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
			resultMap.put("result", "error");
		}else{
			String sessionPwd = ((User)o).getUserPassword();
			if(oldpassword.equals(sessionPwd)){
				resultMap.put("result", "true");
			}else{//旧密码输入不正确
				resultMap.put("result", "false");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping("/modifyexe")
	private String  modify(@ModelAttribute User user,HttpSession session){
		user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		if(userService.modify(user)){
			System.out.println("redirect:/jsp/user/query");
			return "redirect:/jsp/user/query";

		}else{

			System.out.println("usermodify");
			return "usermodify";
		}
	}


	@RequestMapping(value = "/{url}/{id}")
	private String  getUserById(@PathVariable("url") String url,@PathVariable("id")String uid,Model model) {
		if(!StringUtils.isNullOrEmpty(uid)) {
			//调用后台方法得到user对象
			User user = userService.getUserById(uid);
			model.addAttribute("user", user);
			return url;
		}else {
			return "error";
		}
	}


	@RequestMapping(value = "/deluser",method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private String  delUser(@RequestParam("uid") String id){
		Integer delId = 0;
		try{
			delId = Integer.parseInt(id);
		}catch (Exception e) {
			// TODO: handle exception
			delId = 0;
		}
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(delId <= 0){
			resultMap.put("delResult", "notexist");
		}else{

			if(userService.deleteUserById(delId)){
				resultMap.put("delResult", "true");
			}else{
				resultMap.put("delResult", "false");
			}
		}
		
		//把resultMap转换成json对象输出
		return  JSONArray.toJSONString(resultMap);

	}
	
	@RequestMapping("/ucexist")
	@ResponseBody
	private String  userCodeExist(String userCode) {
		//判断用户账号是否可用
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(StringUtils.isNullOrEmpty(userCode)){
			resultMap.put("userCode", "exist");
		}else{
			User user = userService.selectUserCodeExist(userCode);
			if(null != user){
				resultMap.put("userCode","exist");
			}else{
				resultMap.put("userCode", "notexist");
			}
		}
		//把resultMap转为json字符串以json的形式输出
		return JSONArray.toJSONString(resultMap);
	}

	@RequestMapping("/getrolelist")
	@ResponseBody
	private String getRoleList() {
		return JSONArray.toJSONString(roleService.getRoleList());
	}

	@RequestMapping("/query")
	private String query(String method,@RequestParam(value = "queryname",defaultValue = "") String queryname, @RequestParam(value = "queryUserRole",defaultValue = "0") String qUR, @RequestParam(value = "pageIndex",defaultValue = "0")String pageIndex, Model model) {
		//查询用户列
		String queryUserName = queryname;
		String temp = qUR;
		 pageIndex = pageIndex;
		int queryUserRole = 0;

		List<User> userList = null;

		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
		int currentPageNo = 1;

		if(queryUserName == null){
			queryUserName = "";
		}
		if(temp != null && !temp.equals("")){
			queryUserRole = Integer.parseInt(temp);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			return "error" ;
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	int totalPageCount = pages.getTotalPageCount();
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
		model.addAttribute("userList",userList);

		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		System.out.println("哈发发发哈："+roleList);
		model.addAttribute("roleList",roleList);
		model.addAttribute("queryUserName",queryUserName);
		model.addAttribute("queryUserRole",queryUserRole);
		model.addAttribute("totalPageCount",totalPageCount);
		model.addAttribute("totalCount",totalCount);
		model.addAttribute("currentPageNo",currentPageNo);

		return  "userlist";
	}




	@RequestMapping(value = "/add",method = {RequestMethod.GET,RequestMethod.POST})
	private String add(@RequestParam("idCardPhoto") MultipartFile file, @ModelAttribute User user ,
					   HttpSession session,
					   HttpServletRequest req) throws  IOException {
		System.out.println("啦啦");
		// 判断文件是否为空，空则返回失败页面
		if (file.isEmpty()) {
			return "forward:/jsp/useradd.jsp";
		}
		// 获取文件存储路径（绝对路径）
		String path = req.getServletContext().getRealPath("/statics/file");

		// 获取原文件名
		String fileName = file.getOriginalFilename();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String saveName = uuid + "_" + fileName.substring(fileName.lastIndexOf(File.separator) + 1);

		// 创建文件实例
		File filePath = new File(path, saveName);
		// 如果文件目录不存在，创建目录
		if (!filePath.getParentFile().exists()) {
			filePath.getParentFile().mkdirs();
			System.out.println("创建目录" + filePath);
		}
		// 写入文件
		file.transferTo(filePath);
		System.out.println(path+"/"+saveName);
		user.setIdCarPhoto(path+"/"+saveName);
		user.setCreationDate(new Date());
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		if(userService.add(user)){
			return "redirect:/jsp/user/query";

		}else{
			return "forward:/jsp/useradd.jsp";
		}
	}



}
